package cn.edu.swu.miniwebsvr.core;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Server {
    private final Config config = Config.getInstance();
    private final ExecutorService threadPool = Executors.newFixedThreadPool(10);
    private volatile boolean running = true;

    public void start() {
        // TODO: [222024321072045/谢冈兵] 实现 ServerSocket 的创建和监听
        try (ServerSocket serverSocket = new ServerSocket(config.getPort())) {
            System.out.println("MiniWebSvr 启动成功，监听端口：" + config.getPort());

            while (running) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("接收到新的连接：" + clientSocket.getInetAddress());
                    threadPool.execute(new RequestProcessor(clientSocket));
                }catch (IOException e){
                    if (running) {
                        System.err.println("接受连接异常: " + e.getMessage());
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败或运行异常: " + e.getMessage());
        } finally {
            shutdown();
        }
    }

    private boolean isPortAvailable(int port) {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            serverSocket.setReuseAddress(true);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public void shutdown() {
        running = false;
        threadPool.shutdown();
        try {
            if (!threadPool.awaitTermination(5, TimeUnit.SECONDS)) {
                threadPool.shutdownNow();
            }
        } catch (InterruptedException e) {
            threadPool.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

    private static class RequestProcessor implements Runnable {
        private final Socket socket;

        public RequestProcessor(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            // TODO: [222024321072045/谢冈兵] 完善请求处理流程，确保异常安全和资源关闭
            try {
                Parameter request = HttpParser.parse(socket.getInputStream());
                Router router = new Router();
                router.route(request, socket.getOutputStream());

            } catch (Exception e) {
                System.err.println("请求处理异常: " + e.getMessage());
                // TODO: [222024321072045/谢冈兵] 可以在这里实现返回 500 错误页面的逻辑
                try {
                    String errorContent = "<h1>500 Internal Server Error</h1><p>" + e.getMessage() + "</p>";
                    String response = "HTTP/1.1 500 Internal Server Error\r\n" +
                            "Content-Type: text/html; charset=UTF-8\r\n" +
                            "Content-Length: " + errorContent.getBytes().length + "\r\n" +
                            "Connection: close\r\n\r\n" +
                            errorContent;
                    socket.getOutputStream().write(response.getBytes());
                } catch (IOException ex) {
                    System.err.println("发送错误响应失败: " + ex.getMessage());
                }
            } finally {
                try {
                    if (socket != null) socket.close();
                } catch (IOException e) { /* ignore */ }
            }
        }
    }
}
